package com.twu.biblioteca;

import java.io.IOException;
import java.util.Map;

/**
 * Created by thoughtworker on 1/21/14.
 */
public class Menu {
    private Map<String, LibraryAction> options;
    private IOManager ioManager;

    public Menu(Map<String, LibraryAction> options, IOManager ioManager) {

        this.options = options;
        this.ioManager = ioManager;
    }

    public boolean keepGoing() {
        return false;
    }

    public void go() {
        displayOptions();
        try {
            executeUserChoice(getUserOptionChoice());
        } catch (IOException e) {
            ioManager.print("Error Reading Input");
        }
    }

    public void displayOptions() {
        for(LibraryAction option : options.values())
            ioManager.print(option.toString());
    }


    public String getUserOptionChoice() throws IOException {
        return ioManager.getUserInput();
    }

    public void executeUserChoice(String userChoice) throws IOException {
        if(!isValid(userChoice)){
            ioManager.print("Select a valid option!");
            return;
        }
        else{
            options.get(userChoice).performAction();
        }
    }

    private boolean isValid(String userChoice) {
        if (options.containsKey(userChoice))
            return true;
        return false;
    }
}
